import { getToken, setToken, removeToken } from '@/utils/auth'
import { login, getInfo } from '@/api/user'
import { constantRoutes, resetRouter } from '@/router/index'
const state = {

  token: getToken() || '',
  userinfo: {},
  routes: constantRoutes
}
const mutations = {
  settoken(state, newtoken) {
    state.token = newtoken
    setToken(newtoken)
  },
  removetoken(state) {
    state.token = ''
    removeToken()
  },
  userinfo(state, myinfo) {
    state.userinfo = myinfo
  },
  setroutes(state, route) {
    state.routes = [...constantRoutes, ...route]
  }
}
const actions = {
  async login(context, userInfo) {
    const token = await login(userInfo)
    console.log(token)
    context.commit('settoken', token)
  },
  async getUserInfo(context) {
    const user = await getInfo()
    console.log(user)
    context.commit('userinfo', user)
    return user
  },
  logout(context) {
    context.commit('removetoken')
    context.commit('userinfo', {})
    resetRouter()
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

